package com.spzx.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.common.security.annotation.RequiresPermissions;
import com.spzx.product.api.domain.ProductUnit;
import com.spzx.product.service.ProductUnitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/unit")
@Tag(name = "商品单位后台管理")
public class ProductUnitController extends BaseController {
    @Resource
    private ProductUnitService productUnitService;

    @Operation(summary = "分页查询商品单位列表")
    @GetMapping("/list")
    @RequiresPermissions("system:unit:list")
    public TableDataInfo pageList(ProductUnit productUnit) {
        startPage();
        String name = productUnit.getName();
        // 查询商品单位列表
        List<ProductUnit> list = productUnitService.list(new LambdaQueryWrapper<ProductUnit>()
                .eq(name != null, ProductUnit::getName, name));
        return getDataTable(list);
    }

    @Operation(summary = "查询商品单位列表")
    @GetMapping("/listAll")
    @RequiresPermissions("system:unit:listAll")
    public AjaxResult ListAllUnit() {
        List<ProductUnit> list = productUnitService.list();
        return success(list);
    }

    @Operation(summary = "根据id查询商品单位信息")
    @GetMapping("/{id}")
    @RequiresPermissions("system:unit:info")
    public AjaxResult getById(@PathVariable Long id) {
        ProductUnit productUnit = productUnitService.getById(id);
        return success(productUnit);
    }

    @Operation(summary = "批量删除商品单位信息")
    @DeleteMapping("/{ids}")
    @RequiresPermissions("system:unit:remove")
    public AjaxResult deleteByIds(@PathVariable("ids") List<Long> ids) {
        boolean batch = productUnitService.removeBatchByIds(ids);
        return toAjax(batch);
    }

    @Operation(summary = "新增|修改商品单位信息")
    @PostMapping("/saveOrUpdate")
    @RequiresPermissions("system:unit:saveOrUpdate")
    public AjaxResult saveOrUpdate(@Validated @RequestBody ProductUnit productUnit) {
        productUnitService.checkUnitName(productUnit);
        boolean saveOrUpdate = productUnitService.saveOrUpdate(productUnit);
        return toAjax(saveOrUpdate);
    }
}
